﻿#include <GetMessageInterface.h>

//extern speechModuleThread *spmoduleth;
//extern DataSerialportClient *serialPortClient;

/**
 * @brief 构造函数
 */
GetMessageInterface::GetMessageInterface()
{
}

/**
 * @brief 析构函数
 */
GetMessageInterface::~GetMessageInterface()
{}

/** 获取实验日志
 * @brief GetMessageInterface::getExpLog
 * @param module 模块
 * @return
 */
Q_INVOKABLE QVariantList GetMessageInterface:: getExpLog(int module){
    __LOG_FSTART(module);

    QVariantList result;
    switch (module)
    {
    case 1://放靶
        for (const auto &key : StaticProperties::expLogList[0].keys())
        {
            result.append(StaticProperties::expLogList[0].value(key));
        }
        break;
    case 2://打靶
        for (const auto &key : StaticProperties::expLogList[1].keys())
        {
            result.append(StaticProperties::expLogList[1].value(key));
        }
        break;
    case 3://转靶
        for (const auto &key : StaticProperties::expLogList[2].keys())
        {
            result.append(StaticProperties::expLogList[2].value(key));
        }
        break;
    case 4://纯化
        for (const auto &key : StaticProperties::expConcurrencyLogList.keys())
        {
            result.append(StaticProperties::expConcurrencyLogList.value(key));
        }
        for (const auto &key : StaticProperties::expLogList[3].keys())
        {
            result.append(StaticProperties::expLogList[3].value(key));
        }
        break;
    }

    __LOG_FEND("LogLength:" + QString::number(result.size()));

    return result;
}

/** 根据模块和实验名称 获取实验日志
 * @brief GetMessageInterface::getExperimentLog
 * @param module 模块 1:放靶 2:打靶 3:转靶 4:纯化
 * @param isMain 全流程 0是
 * @param name 实验名称
 * @return
 */
Q_INVOKABLE QVariantList GetMessageInterface::getExperimentLog(int module,int isMain,QString name){

    __LOG_FSTART(QString::number(module) + QString(" ") + QString::number(isMain) + " " + name);

    QVariantList result;
    if(isMain==0)//全流程
    {
        result = getExpLog(module);
        __LOG_FEND(result);
        return  result;
    }
    else
    {
        stepNum=1;

        switch (module)
        {
        case 1:
            StaticProperties::expLogList[0].clear();
            result = getReleasseTargetLog(name);
            __LOG_FEND(result);
            return  result;
        case 2:
            StaticProperties::expLogList[1].clear();
            result = getPracticeTargetLog(name);
            __LOG_FEND(result);
            return  result;
        case 3:
            StaticProperties::expLogList[2].clear();
            result = getShiftingTargetLog(name);
            __LOG_FEND(result);
            return  result;
        case 4:
            StaticProperties::expConcurrencyLogList.clear();
            StaticProperties::expLogList[3].clear();
            result = getPurifyingLog(name,false);
            __LOG_FEND(result);
            return  result;
        }
    }
    __LOG_FEND("LogLength:" + QString::number(result.size()));
    return result;
}

/** 刷新流程实验日志
 * @brief GetMessageInterface::refMainExpLog
 * @param name 实验名称
 */
Q_INVOKABLE void GetMessageInterface::refMainExpLog(QString name)
{
    __LOG_FSTART(name);

    if(!StaticProperties::expRecovery){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QString sql = QString("Select ReleasseTargetExp,PracticeTargetExp,ShiftingTargetExp,PurifyingExp From MainExperimentalProcess Where ExperimentName='%1'").arg(name);
        query.exec(sql);
        __LOG_DEBUG("ExecEnd");

        QString ReleasseTargetExp,PracticeTargetExp,ShiftingTargetExp,PurifyingExp;

        while (query.next()) {
            ReleasseTargetExp = query.value("ReleasseTargetExp").toString();
            PracticeTargetExp = query.value("PracticeTargetExp").toString();
            ShiftingTargetExp = query.value("ShiftingTargetExp").toString();
            PurifyingExp = query.value("PurifyingExp").toString();
        }
        __LOG_DEBUG("QueryEnd");

        stepNum=1;
        unionStep=1;
        StaticProperties::expLogList[0].clear();
        StaticProperties::expLogList[1].clear();
        StaticProperties::expLogList[2].clear();
        StaticProperties::expLogList[3].clear();
        StaticProperties::expConcurrencyLogList.clear();
        __LOG_DEBUG("ClearEnd");

        getReleasseTargetLog(ReleasseTargetExp);
        getPracticeTargetLog(PracticeTargetExp);
        getShiftingTargetLog(ShiftingTargetExp);
        getPurifyingLog(PurifyingExp,false);
    }

    __LOG_FEND__;
}

/** 获取放靶实验日志
 * @brief GetMessageInterface::getReleasseTargetLog
 * @param name 实验名称
 * @return
 */
QVariantList GetMessageInterface::getReleasseTargetLog(QString name){

    __LOG_FSTART(name);

    QVariantList result;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Select ID From fbexe_config where value_1='%1' and type=0").arg(name);
    query.exec(sql);
    QString id;
    while (query.next()) {
        id=query.value("ID").toString();
    }
    sql=QString("Select * From fbexe_config Where id='%1' and type<>'0' order by step").arg(id);
    query.exec(sql);

    while (query.next())
    {
        QVariantMap map;
        map["FinishTime"]="";
        map["Step"]=QString::number(stepNum);

        QString actionInfo;
        QString memo = "";           // 导出报告里面，ReportDetail加了一列备注[20251119-JNN]
        switch (query.value("Type").toInt())
        {
        case 1:
            actionInfo=query.value("value_1").toString()=="打开"?"打开挡板":"遮挡挡板";
            break;
        case 2:
            actionInfo=query.value("value_1").toString();
            memo = "位置:" +  query.value("value_2").toString();      // [20251119-JNN]
            break;
        case 3:
            actionInfo =query.value("value_1").toString()+"夹爪";
            break;
        case 5:
            actionInfo="热室端送靶";
            break;
        case 7:
            if(query.value("value_1").toInt()==0){
                actionInfo="等待"+query.value("value_2").toString()+"秒";
            }
            else{
                actionInfo="等待前置步骤"+QString::number(stepNum-(query.value("step").toInt()-query.value("value_3").toInt()))+"执行完成";
            }
            break;
        case 8:
            actionInfo="实验暂停,需点击继续";
            break;
        case 9:
            actionInfo="联动"+query.value("Value_1").toString()+"模块中的"+query.value("Value_3").toString()+"实验";
            break;
        }
        map["ActionInfo"]=actionInfo;
        map["Time"]="0";
        map["Status"]="未执行";
        map["Memo"] = memo;
        StaticProperties::expLogList[0].insert(stepNum,map);
        stepNum++;

        result.append(map);
    }
    __LOG_FEND(result.size());
    return  result;
}

/** 获取打靶实验日志
 * @brief GetMessageInterface::getPracticeTargetLog
 * @param name 实验名称
 * @return
 */
QVariantList GetMessageInterface::getPracticeTargetLog(QString name){
    __LOG_FSTART(name);
    QVariantList result;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Select ID From dbexe_config where value_1='%1' and type=0").arg(name);
    query.exec(sql);
    QString id;
    while (query.next()) {
        id=query.value("ID").toString();
    }
    sql=QString("Select * From dbexe_config Where id='%1' and type<>'0' order by step").arg(id);
    query.exec(sql);

    while (query.next())
    {
        QVariantMap map;
        map["FinishTime"]="";
        map["Step"]=stepNum;
        QString actionInfo;
        QString memo = "";           // 导出报告里面，ReportDetail加了一列备注[20251119-JNN]
        switch (query.value("Type").toInt())
        {
        case 1:
            actionInfo=query.value("value_1").toString()=="开启"?"开启吸取梭体":"关闭吸取梭体";
            break;
        case 2:
            actionInfo=query.value("value_1").toString()=="开"?"开始冷却":"关闭冷却";
            memo = "氦气开关:" + query.value("value_2").toString();      // [20251119-JNN]
            break;
        case 3:
            actionInfo="干燥"+query.value("value_1").toString()+"分钟";
            break;
        case 4:
            actionInfo=query.value("value_1").toString();
            break;
        case 5:
            actionInfo=query.value("value_1").toString();//抱闸状态
            break;
        case 6:
            actionInfo=query.value("value_1").toString()=="下移"?"梭体上靶下移":"梭体上靶上移";
            break;
        case 7:
            actionInfo="热室端送靶";
            break;
        case 8:
            if(query.value("value_1").toInt()==0){
                actionInfo="等待"+query.value("value_2").toString()+"秒";
            }
            else{
                actionInfo="等待前置步骤"+QString::number(stepNum-(query.value("step").toInt()-query.value("value_3").toInt()))+"执行完成";
            }
            break;
        case 9:
            actionInfo="实验暂停,需点击继续";
            break;
        case 10:
            actionInfo="联动纯化实验";
            map["ActionInfo"]=actionInfo;
            map["Time"]="0";
            map["Status"]="未执行";
            map["Memo"] = memo;
            StaticProperties::expLogList[1].insert(stepNum,map);
            stepNum++;
            result.append(map);

            if(query.value("Value_1").toString()=="纯化")
            {
                getPurifyingLog(query.value("Value_3").toString(),query.value("value_4").toString()=="是");
            }
            break;
        }
        if(query.value("Type").toInt()!=10){
            map["ActionInfo"]=actionInfo;
            map["Time"]="0";
            map["Status"]="未执行";
            map["Memo"] = memo;
            StaticProperties::expLogList[1].insert(stepNum,map);
            stepNum++;
            result.append(map);
        }
    }
    __LOG_FEND(result.size());
    return  result;
}

/** 获取转靶实验日志
 * @brief GetMessageInterface::getShiftingTargetLog
 * @param name 实验名称
 * @return
 */
QVariantList GetMessageInterface::getShiftingTargetLog(QString name){
    __LOG_FSTART(name);
    QVariantList result;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Select ID From zbexe_config where value_1='%1' and type=0").arg(name);
    query.exec(sql);
    QString id;
    while (query.next()) {
        id=query.value("ID").toString();
    }
    sql=QString("Select * From zbexe_config Where id='%1' and type<>'0' order by step").arg(id);
    query.exec(sql);

    while (query.next())
    {
        QVariantMap map;
        map["FinishTime"]="";
        map["Step"]=stepNum;

        QString actionInfo;
        QString memo = "";           // 导出报告里面，ReportDetail加了一列备注[20251119-JNN]

        switch (query.value("Type").toInt())
        {
        case 1:
            actionInfo=query.value("value_1").toString()=="遮挡"?"遮蔽挡板":"打开挡板";
            break;
        case 2:
            actionInfo=query.value("value_1").toString();
            memo = "位置:" +  query.value("value_2").toString();      // [20251119-JNN]
            break;
        case 3:
            actionInfo =query.value("value_1").toString()+"夹爪";
            break;
        case 4:
            actionInfo =query.value("value_1").toString();
            break;
        case 5:
            actionInfo=query.value("value_1").toString()=="开启"?"开启热室端送靶":"关闭热室端送靶";
            break;
        case 6:
            actionInfo =query.value("value_1").toString();
            if(actionInfo != "关闭"){
                memo += "速度(r/m):" +  query.value("value_2").toString();      // [20251119-JNN]
                memo += "; 时间(s):" +  query.value("value_3").toString();      // [20251119-JNN]
            }
            break;
        case 7:
            if(query.value("value_1").toInt()==0){
                actionInfo="等待"+query.value("value_2").toString()+"秒";
            }
            else{
                actionInfo="等待前置步骤"+QString::number(stepNum-(query.value("step").toInt()-query.value("value_3").toInt()))+"执行完成";
            }
            break;
        case 8:
            actionInfo="实验暂停,需点击继续";
            break;
        case 9:
            actionInfo="联动纯化实验";
            map["ActionInfo"]=actionInfo;
            map["Time"]="0";
            map["Status"]="未执行";
            map["Memo"] = memo;     // [20251119-JNN]
            StaticProperties::expLogList[2].insert(stepNum,map);
            stepNum++;
            result.append(map);

            if(query.value("Value_1").toString()=="纯化")
            {
                getPurifyingLog(query.value("Value_3").toString(),query.value("value_3").toString()=="是");
            }
            break;
        case 10:
            actionInfo="活性检测模块"+query.value("Value_1").toString();
            break;
        case 11:
            actionInfo="旋盖夹爪"+query.value("Value_1").toString();
            break;
        }
        if(query.value("Type").toInt()!=9){
            map["ActionInfo"]=actionInfo;
            map["Time"]="0";
            map["Status"]="未执行";
            map["Memo"] = memo;     // [20251119-JNN]
            StaticProperties::expLogList[2].insert(stepNum,map);
            stepNum++;
            result.append(map);
        }
    }

    __LOG_FEND(result.size());
    return  result;
}

/** 获取纯化日志
 * @brief GetMessageInterface::getPurifyingLog
 * @param name 实验名称
 * @return
 */
QVariantList GetMessageInterface::getPurifyingLog(QString name,bool concurrencyUnion)
{
    __LOG_FSTART(name);
    QVariantList result;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString sql=QString("Select ID From exe_config where value_1='%1' and type=0").arg(name);
    query.exec(sql);
    QString id;
    while (query.next()) {
        id=query.value("ID").toString();
    }
    sql=QString("Select * From exe_config Where id='%1' and type<>'0' order by step").arg(id);
    query.exec(sql);

    while (query.next())
    {
        QVariantMap map;
        map["FinishTime"]="";
        map["Step"]=concurrencyUnion?"并发"+QString::number(unionStep):QString::number(stepNum);
        QString actionInfo;
        QString memo = "";           // 导出报告里面，ReportDetail加了一列备注[20251119-JNN]
        if(query.value("Type").toString()=="1")
        {
            actionInfo="注射器"+query.value("Value_1").toString()+query.value("Value_4").toString();
            memo += "注射器类型:" + query.value("Value_3").toString();
            memo += "; 动作:" + query.value("Value_4").toString();
            memo += "; 距离:" + query.value("Value_6").toString();
            memo += "; 体积:" + query.value("Value_5").toString();
            memo += "; 速度:" + query.value("Value_8").toString() + query.value("Value_9").toString();
            if(query.value("Value_7").toString()!=""){
                memo += "; 位置偏差:" + query.value("Value_7").toString();
            }
        }
        else if(query.value("Type").toString()=="2")
        {
            if(query.value("Value_1").toString()=="开启"){
                QList<QString> openList=query.value("Value_2").toString().split(",");
                if(openList.length()>0 && !openList[0].isEmpty())
                {
                    actionInfo+="打开阀门";

                    for(int i=0;i<openList.length();i++)
                    {
                        actionInfo+=openList[i]+",";
                    }
                }
                else
                {
                    actionInfo+="关闭全部阀门";
                }
            }
        }
        else if(query.value("Type").toString()=="3")
        {
            actionInfo="转盘转到"+query.value("value_1").toString()+"号位置";
        }
        else if(query.value("Type").toString()=="4")
        {
            actionInfo="盖盖";
        }
        else if(query.value("Type").toString()=="5"){
            actionInfo="检测器";
        }
        else if(query.value("Type").toString()=="6"){
            actionInfo =query.value("value_1").toString();
        }
        else if(query.value("Type").toString()=="7"){
            if(query.value("value_1").toInt()==0){
                actionInfo="等待"+query.value("value_2").toString()+"秒";
            }
            else{
                actionInfo="等待前置步骤"+QString::number(stepNum-(query.value("step").toInt()-query.value("value_3").toInt()))+"执行完成";
            }
        }
        else if(query.value("Type").toString()=="8")
        {
            actionInfo="循环执行步骤"+query.value("Value_1").toString()+"到"+"步骤"+query.value("Value_2").toString()+","+query.value("Value_3").toString()+"次";
        }
        else if(query.value("Type").toString()=="9"){
            actionInfo="跳到步骤"+query.value("Value_1").toString();
        }
        else if(query.value("Type").toString()=="10"){
            actionInfo="暂停";
        } else if(query.value("Type").toString()=="11"){
            actionInfo=query.value("Value_1").toString()+"°加热"+query.value("Value_2").toString()+"秒";
        }

        map["ActionInfo"]=actionInfo;
        map["Time"]="0";
        map["Status"]="未执行";
        map["Memo"] = memo;             // [20251119-JNN]
        if(concurrencyUnion){
            StaticProperties::expConcurrencyLogList.insert(unionStep,map);
            unionStep++;
        }
        else{
            StaticProperties::expLogList[3].insert(stepNum,map);
            stepNum++;
        }
        result.append(map);

    }
    __LOG_FEND(result);
    return  result;
}

/** 获取实验信息
 * @brief GetMessageInterface::setExpBaseInfo
 * @param map 实验信息
 */
Q_INVOKABLE void GetMessageInterface::setExpBaseInfo(QVariantMap map)
{
    __LOG_FSTART(map);

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString serial;
    QString sql="Select max(Serial)+1 as Serial From ReportInfo";
    query.exec(sql);
    while (query.next()) {
        serial=query.value("Serial").toString().isNull()?"1":query.value("Serial").toString();
    }

    QString expType;
    switch (StaticProperties::currentExpType)
    {
    case 0:
        expType="全流程";
        if(StaticProperties::softType==0){
            saveReleaseReportInfo(serial);
            savePracticeReportInfo(serial);
            saveShiftingReportInfo(serial);
            savePurifyingReportInfo(serial);
        }
        else if(StaticProperties::softType==1){
            saveReleaseReportInfo(serial);
            savePracticeReportInfo(serial);
            saveShiftingReportInfo(serial);
        }

        break;
    case 1:
        expType="放靶";
        saveReleaseReportInfo(serial);
        break;
    case 2:
        expType="打靶";
        savePracticeReportInfo(serial);
        break;
    case 3:
        expType="转靶";
        saveShiftingReportInfo(serial);
        break;
    case 4:
        expType="纯化";
        savePurifyingReportInfo(serial);
        break;
    }

    // 旧版ReportInfo
//    sql=QString("Insert into ReportInfo(Serial,ExpName,EquName,ExpDate,Operator,Memo,ExpType,ExpFlowName,ConsumableName,ConsumableCode) Values"
//                "('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10')").arg(
//                serial,map.value("ExpName").toString(),
//                map.value("EquName").toString(),map.value("Date").toString(),
//                map.value("Operator").toString(),map.value("Memo").toString(),
//                expType,StaticProperties::currentExpName,
//                CommonHelper::Common().getItemName("3",StaticProperties::currentExpConsumables),
//                map.value("ConsumableCode").toString());

    // 新版ReportInfo [20251119-JNN]
    sql=QString("Insert into ReportInfo(Serial,ExpName,EquName,ExpStartTime,Operator,Memo,ExpType,ConsumableName,ConsumableCode,SampleHalfLife) Values"
                "('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10')").arg(
                serial,
                map.value("ExpName").toString(),
                map.value("EquName").toString(),
                CommonHelper::Common().GetDateTimeStr(),
                map.value("Operator").toString(),
                map.value("Memo").toString(),
                map.value("ExpType").toString(),
                CommonHelper::Common().getItemName("3",StaticProperties::currentExpConsumables),
                map.value("ConsumableCode").toString(),
                "00:16:00");


    query.exec(sql);
    __LOG_FEND__;
}

/** 保存放靶实验日志
 * @brief GetMessageInterface::saveReleaseReportInfo
 * @param serial 序号
 */
void GetMessageInterface::saveReleaseReportInfo(QString serial)
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    db.transaction();
    for (auto outerIt = StaticProperties::expLogList[0].constBegin(); outerIt != StaticProperties::expLogList[0].constEnd(); ++outerIt) {
        const QVariantMap &innerMap = outerIt.value();
        QString sql=QString("Insert into ReportDetail Values('%1','1','%2','%3','%4','%5','%6','%7')").arg(
                    serial,innerMap["FinishTime"].toString(),
                innerMap["Step"].toString(),innerMap["ActionInfo"].toString(),
                innerMap["Time"].toString(),innerMap["Status"].toString(),innerMap["Memo"].toString());       //[20251119-JNN]
        query.exec(sql);
    }
    db.commit();
}

/** 保存打靶实验日志
 * @brief GetMessageInterface::savePracticeReportInfo
 * @param serial 序号
 */
void GetMessageInterface::savePracticeReportInfo(QString serial)
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    db.transaction();
    for (auto outerIt = StaticProperties::expLogList[1].constBegin(); outerIt !=  StaticProperties::expLogList[1].constEnd(); ++outerIt) {
        const QVariantMap &innerMap = outerIt.value();
        QString sql=QString("Insert into ReportDetail Values('%1','2','%2','%3','%4','%5','%6','%7')").arg(
                    serial,innerMap["FinishTime"].toString(),
                innerMap["Step"].toString(),innerMap["ActionInfo"].toString(),
                innerMap["Time"].toString(),innerMap["Status"].toString(),innerMap["Memo"].toString());     // [20251119-JNN]
        query.exec(sql);
    }
    db.commit();
}

/** 保存转靶实验日志
 * @brief GetMessageInterface::saveShiftingReportInfo
 * @param serial 序号
 */
void GetMessageInterface::saveShiftingReportInfo(QString serial)
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    db.transaction();
    for (auto outerIt = StaticProperties::expLogList[2].constBegin(); outerIt !=  StaticProperties::expLogList[2].constEnd(); ++outerIt) {
        const QVariantMap &innerMap = outerIt.value();
        QString sql=QString("Insert into ReportDetail Values('%1','3','%2','%3','%4','%5','%6','%7')").arg(
                    serial,innerMap["FinishTime"].toString(),
                innerMap["Step"].toString(),innerMap["ActionInfo"].toString(),
                innerMap["Time"].toString(),innerMap["Status"].toString(),innerMap["Memo"].toString());     // [20251119-JNN]
        query.exec(sql);
    }
    db.commit();
}

/** 保存纯化实验日志
 * @brief GetMessageInterface::savePurifyingReportInfo
 * @param serial 序号
 */
void GetMessageInterface::savePurifyingReportInfo(QString serial)
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    db.transaction();
    for (auto outerIt = StaticProperties::expLogList[3].constBegin(); outerIt !=  StaticProperties::expLogList[3].constEnd(); ++outerIt) {
        const QVariantMap &innerMap = outerIt.value();
        QString sql=QString("Insert into ReportDetail Values('%1','4','%2','%3','%4','%5','%6','%7')").arg(
                    serial,innerMap["FinishTime"].toString(),
                innerMap["Step"].toString(),innerMap["ActionInfo"].toString(),
                innerMap["Time"].toString(),innerMap["Status"].toString(),innerMap["Memo"].toString());     // [20251119-JNN]
        query.exec(sql);
    }

    for (auto outerIt = StaticProperties::expConcurrencyLogList.constBegin(); outerIt !=  StaticProperties::expConcurrencyLogList.constEnd(); ++outerIt) {
        const QVariantMap &innerMap = outerIt.value();
        QString sql=QString("Insert into ReportDetail Values('%1','4','%2','%3','%4','%5','%6','%7')").arg(
                    serial,innerMap["FinishTime"].toString(),
                innerMap["Step"].toString(),innerMap["ActionInfo"].toString(),
                innerMap["Time"].toString(),innerMap["Status"].toString(),innerMap["Memo"].toString());     // [20251119-JNN]
        query.exec(sql);
    }
    db.commit();
}

/** 获取实验步数
 * @brief GetMessageInterface::getExperimentStepCount
 * @param module 模块
 * @return
 */
Q_INVOKABLE int GetMessageInterface::getExperimentStepCount(int module)
{
    __LOG_FSTART(module);
    int res;
    switch (module)
    {
    case 0:
        if(StaticProperties::softType==0){
            res = StaticProperties::expLogList[3].size()==0 ? 0 : StaticProperties::expLogList[3].lastKey();
        }
        else{
            res = StaticProperties::expLogList[2].size()==0 ? 0 : StaticProperties::expLogList[2].lastKey();
        }
        break;
    case 1:
        res = StaticProperties::expLogList[0].size()==0 ? 0 :StaticProperties::expLogList[0].lastKey();
        break;
    case 2:
        res = StaticProperties::expLogList[1].size()==0 ? 0 :StaticProperties::expLogList[1].lastKey();
        break;
    case 3:
        res = StaticProperties::expLogList[2].size()==0 ? 0 :StaticProperties::expLogList[2].lastKey();
        break;
    case 4:
        res = StaticProperties::expLogList[3].size()==0 ? 0 :StaticProperties::expLogList[3].lastKey();
        break;
    default:
        res = 0;
    }

    __LOG_FEND(res);
    qDebug()<<res;
    return res;
}

/** 获取实验时间
 * @brief GetMessageInterface::getExperimentTotalTime
 * @return
 */
Q_INVOKABLE int GetMessageInterface::getExperimentTotalTime(){

    __LOG_FSTART__;
    int res = qRound(StaticProperties::totalExpTime);
    __LOG_FEND(res);
    return res;
}

/** 连接设备
 * @brief GetMessageInterface::connectEqu
 * @param connectType 连接类型
 * @param ip
 * @param port
 */
Q_INVOKABLE void GetMessageInterface::connectEqu(QString connectType, QString ip,QString port){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Update IpInfo set Ip='%1',port='%2',IsDefault='1' Where ConnectType='%3'").arg(ip,port,connectType);
    query.exec(sql);
    sql=QString("Update IpInfo Set IsDefault='0' Where ConnectType<>'%1'").arg(connectType);
    query.exec(sql);
    if(connectType=="0"){
        udpClient= UdpClient::getInstance();
        udpClient->ClientConnectToHost(ip, port.toInt());
        cpsUdpClient=CpsUdpClient::getInstance();
        cpsUdpClient->ClientConnectToHost(ip, 8090);
        QString sendInfo=CommCommand::I().connectToLc();
        udpClient->ClientSendingData(CommonHelper::Common().GetSendData(sendInfo));
    }
}

/** 获取默认连接信息
 * @brief GetMessageInterface::getDefaultConnectInfo
 * @return
 */
Q_INVOKABLE int GetMessageInterface::getDefaultConnectInfo()
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="Select ConnectType From IpInfo Where IsDefault='1'";
    query.exec(sql);
    int type;
    while (query.next()) {
        type=query.value("ConnectType").toInt();
    }
    return type;
}

/** 根据类型查询连接信息
 * @brief GetMessageInterface::getConnectInfo
 * @param connectType 连接类型
 * @return
 */
Q_INVOKABLE QVariantMap GetMessageInterface::getConnectInfo(int connectType){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QVariantMap map;

    QString sql=QString("Select Ip,Port From IpInfo where ConnectType='%1'").arg(connectType);
    query.exec(sql);
    while (query.next()) {
        map["Ip"]=query.value("Ip").toString();
        map["Port"]=query.value("Port").toString();
    }

    return map;
}

Q_INVOKABLE void GetMessageInterface::readOrWriteConnectInfo(QString type,QString ip,QString port){
    QString sendInfo= CommCommand::I().connectData(type,ip,port);
    udpClient->ClientSendingData(CommonHelper::Common().GetSendData(sendInfo));
    if(type=="1"){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QString sql=QString("Update IpInfo set Ip='%1',port='%2',IsDefault='1' Where ConnectType='0'").arg(ip,port);
        query.exec(sql);
    }
}

/** 单位转换
 * @brief GetMessageInterface::unitConversion
 * @param num 原始值
 * @param diameter 直径
 * @param unit 单位
 * @return
 */
Q_INVOKABLE QString GetMessageInterface::unitConversion(QString num,QString diameter,QString unit)
{
    if(unit=="mL/Min")
    {
        return CommonHelper::Common().secondToMin(num,diameter);
    }
    else
    {
        return CommonHelper::Common().minToSecond(num,diameter);
    }
}

/**
 * @brief GetMessageInterface::unitConversionBySerial
 * @param num
 * @param type
 * @param serial
 * @param unit
 * @return
 */
Q_INVOKABLE QString GetMessageInterface::unitConversionBySerial(QString num,QString type,QString serial,QString unit)
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Select InsideDiameter From SyringeMaintenance Where ConsumablesTypes='%1' and Id='%2'").arg(CommonHelper::Common().getItemCode("3",type),serial);
    QString diameter;
    query.exec(sql);
    while (query.next()) {
        diameter=query.value("InsideDiameter").toString();
    }
    return unitConversion(num,diameter,unit);
}

/** 主页实验流程
 * @brief GetMessageInterface::getMainMethodList
 * @return
 */
Q_INVOKABLE QStringList GetMessageInterface::getMainMethodList()
{
    __LOG_FSTART__;

    QStringList result;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="Select distinct ExperimentName From MainExperimentalProcess";
    query.exec(sql);
    while (query.next())
    {
        result.append(query.value("ExperimentName").toString());
    }

    __LOG_FEND(result);
    return result;
}

/** 获取主流程耗材类型
 * @brief GetMessageInterface::getConsumableByMainMethod
 * @param expName 实验名称
 * @return
 */
Q_INVOKABLE QString GetMessageInterface::getConsumableByMainMethod(QString expName)
{
    __LOG_FSTART(expName);

    QString result;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Select value_2 From exe_config Where value_1 =(Select PurifyingExp From MainExperimentalProcess Where ExperimentName='%1') and type=0").arg(expName);
    query.exec(sql);
    while (query.next())
    {
        result=CommonHelper::Common().getItemName("3", query.value("value_2").toString());
    }

    __LOG_FEND(result);
    return result;
}

/** 获取耗材列表
 * @brief GetMessageInterface::getConsumableList
 * @return
 */
Q_INVOKABLE QStringList GetMessageInterface::getConsumableList()
{
    __LOG_FSTART__;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="Select Distinct value From Deftab Where Id=3";
    query.exec(sql);
    QStringList result;
    while (query.next()) {
        result.append(query.value("value").toString());
    }

    __LOG_FEND(result);

    return  result;
}

/** 查询流程实验名称
 * @brief GetMessageInterface::getSingleMethodByMainMethod
 * @param expName
 * @return
 */
Q_INVOKABLE QStringList GetMessageInterface::getSingleMethodByMainMethod(QString expName)
{
    __LOG_FSTART(expName);

    QStringList result;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql = QString("Select ReleasseTargetExp,PracticeTargetExp,ShiftingTargetExp,PurifyingExp From MainExperimentalProcess Where ExperimentName='%1'").arg(expName);
    query.exec(sql);
    while (query.next()) {
        result.append(query.value("ReleasseTargetExp").toString());
        result.append(query.value("PracticeTargetExp").toString());
        result.append(query.value("ShiftingTargetExp").toString());
        result.append(query.value("PurifyingExp").toString());
    }

    __LOG_FEND(result);
    return  result;
}

/** 根据类型获取所有实验名称
 * @brief GetMessageInterface::getSingleMethodList
 * @param module 模块
 * @param consumable 耗材
 * @return
 */
Q_INVOKABLE QStringList GetMessageInterface::getSingleMethodList(int module,QString consumable)
{
    __LOG_FSTART(QString::number(module) + consumable);

    QStringList result;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql;
    switch (module)
    {
    case 1:
        sql="Select distinct value_1 From fbexe_config Where type='0'";
        break;
    case 2:
        sql="Select distinct value_1 From dbexe_config Where type='0'";
        break;
    case 3:
        sql="Select distinct value_1 From zbexe_config Where type='0'";
        break;
    case 4:
        if(consumable==""){
            sql="Select Distinct value_1 From exe_config Where type='0'";
        }
        else
        {
            QString code = CommonHelper::Common().getItemCode("3",consumable);
            sql=QString("Select Distinct value_1 From exe_config Where type='0' and value_2='%1'").arg(code);
        }
        break;
    }
    query.exec(sql);
    while (query.next())
    {
        result.append(query.value("value_1").toString());
    }

    __LOG_FEND(result);

    return  result;
}

/** 设置实验信息
 * @brief GetMessageInterface::setExpInfo
 * @param module 模块
 * @param expName 实验名称
 * @param type 实验类型
 * @return
 */
Q_INVOKABLE QString GetMessageInterface::setExpInfo(int module,QString expName,QString type)
{
    __LOG_FSTART(QString::number(module) + QString(" ") +expName + " " + type);
    StaticProperties::currentExpType=module;//实验类型 0:总流程 1:放靶 2:打靶 3:转靶 4:纯化
    StaticProperties::currentExpName=expName;

    QString newConsumables=CommonHelper::Common().getItemCode("3",type);
    if(StaticProperties::currentExpConsumables!=newConsumables){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        QString sql=QString("Update ModuleResetStatus set Status=0 Where module=4");
        query.exec(sql);
    }
    StaticProperties::currentExpConsumables=newConsumables;
    return "";
    __LOG_FEND__;
}

/** 确认耗材
 * @brief GetMessageInterface::confirmClicked
 * @param type 耗材
 */
Q_INVOKABLE void GetMessageInterface::confirmClicked(QString type){
    qDebug() << "确认耗材" << type;
    __LOG_FSTART(type);
    QString info= CommCommand::I().reset("1","9",CommonHelper::Common().getItemCode("3",type));
    udpClient= UdpClient::getInstance();
    udpClient->ClientSendingData(CommonHelper::Common().GetSendData(info));

    __LOG_FEND__;
}

/** 获取报告数据
 * @brief GetMessageInterface::getReportInfo
 * @return
 */
Q_INVOKABLE QVariantList GetMessageInterface::getReportInfo()
{
    __LOG_FSTART__;

    QVariantList resultList;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="Select Serial,ExpName,ExpStartTime,ExpType From ReportInfo order by Serial desc";
    query.exec(sql);

    while (query.next()) {
        QVariantList map;
        for (int i = 0; i < query.record().count(); ++i) {
            map.push_back(query.value(i));
        }
        resultList.push_back(map);
    }
    __LOG_FEND(resultList.size());
    return resultList;
}

/** 获取报告基本信息
 * @brief GetMessageInterface::getReportBaseInfo
 * @param serial 序号
 * @return
 */
Q_INVOKABLE QVariantMap  GetMessageInterface::getReportBaseInfo(int serial)
{
    __LOG_FSTART(serial);

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    // [20251119-JNN] 改为新版导出报告的基础信息
    QString sql=QString("Select ExpName,EquName,ExpStartTime,ExpEndTime,ExpDuration,Operator,Memo,"
                        "ConsumableName,ConsumableCode,ExpType,SampleHalfLife,HalfLifeDate,ValveStartTime,ValveDelayTime,ValveEndTime From ReportInfo Where "
                        "Serial='%1'").arg(QString::number(serial));
    query.exec(sql);
    QVariantMap map;
    while (query.next())
    {
        for (int i = 0; i < query.record().count(); ++i) {
            map[query.record().fieldName(i)] = query.value(i);
        }
    }
    __LOG_FEND(map);
    return map;
}

/** 获取报告详细信息
 * @brief GetMessageInterface::getReportDetail
 * @param serial 序号
 * @return
 */
Q_INVOKABLE QVariantList GetMessageInterface::getReportDetail(int serial)
{
    __LOG_FSTART(serial);
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Select FinishTime, Step, ActionInfo, Time, Status, Memo From ReportDetail Where ReportSerial='%1'").arg(QString::number(serial));
    query.exec(sql);
    QVariantList resultList;

    while (query.next()) {
        QVariantList map;
        for (int i = 0; i < query.record().count(); ++i) {
            map.push_back(query.value(i));
        }
        resultList.push_back(map);
    }
    __LOG_FEND(resultList.size());
    return resultList;
}

/** 删除报告
 * @brief GetMessageInterface::delReportInfo
 * @param serial
 */
Q_INVOKABLE void GetMessageInterface::delReportInfo(int serial)
{
    __LOG_FSTART(serial);
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql;
    if(serial==0){
        sql="Delete From ReportInfo";
        query.exec(sql);

        sql="Delete From ReportDetail";
        query.exec(sql);
    }
    else
    {
        sql=QString("Delete From ReportInfo Where Serial='%1'").arg(QString::number(serial));
        query.exec(sql);

        sql=QString("Update ReportInfo set Serial=Serial-1 Where Serial>'%1'").arg(QString::number(serial));
        query.exec(sql);

        sql=QString("Delete From ReportDetail Where ReportSerial='%1'").arg(QString::number(serial));
        query.exec(sql);

        sql=QString("Update ReportDetail set ReportSerial=ReportSerial-1 Where ReportSerial>'%1'").arg(QString::number(serial));
        query.exec(sql);
    }
    __LOG_FEND__;
}

/** 设置语音助手是否启用
 * @brief GetMessageInterface::setSpeechUseInfo
 * @param info
 */
Q_INVOKABLE void GetMessageInterface::setSpeechUseInfo(QString info){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql=QString("Update SpeechMode Set IsUse='%1'").arg(info);
    query.exec(sql);
}

/** 连接语音助手
 * @brief GetMessageInterface::connectSpeechMode
 * @param serialPort
 */
Q_INVOKABLE void GetMessageInterface::connectSpeechMode(QString serialPort){
    //    QSqlDatabase db = dbHelper::openConnection();
    //    QSqlQuery query(db);
    //    QString sql=QString("Update SpeechMode Set SerialPort='%1'").arg(serialPort);
    //    query.exec(sql);
    //    spmoduleth->serialinfo();
}

/** 获取语音助手状态
 * @brief GetMessageInterface::getSpeechUseInfo
 * @return
 */
Q_INVOKABLE int GetMessageInterface::getSpeechUseInfo(){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql="Select IsUse From SpeechMode";
    query.exec(sql);
    int result=0;
    while (query.next()) {
        result=query.value("IsUse").toInt();
    }
    return  result;

}

/** 获取端口
 * @brief GetMessageInterface::getSerialPort
 * @return
 */
Q_INVOKABLE QStringList GetMessageInterface::getSerialPort(){
    __LOG_FSTART__;
    QStringList result;
    foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts()) {
        result.append(info.portName());
    }
    __LOG_FEND(result);
    return result;
}

/** 获取统计数据
 * @brief GetMessageInterface::getStaticNum
 * @param type
 * @param beginTime
 * @param endTime
 * @return
 */
Q_INVOKABLE QStringList GetMessageInterface::getStaticNum(int type,QString beginTime,QString endTime){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString info;
    switch (type) {
    case 1:
        info="EquOperatingTime";
        break;
    case 2:
        info="ExperimentalRunningTime";
        break;
    case 3:
        info="TargetPeristalticPump";
        break;
    case 4:
        info="PurifyingPeristalticPump";
        break;
    case 5:
        info="CompressRubberPadTimes";
        break;
    case 6:
        info="VacuumSuctionCupUseTime";
        break;
    case 7:
        info="ExpansionClipUseTime";
        break;
    case 8:
        info="ClawUsageDuration";
        break;
    }
    QStringList result;
    QString sql=QString("SELECT strftime('%Y-%m', StaticDate) AS Month,"
                        "sum(%1) AS TotalRecords "
                        "FROM DataStatistics "
                        "where Month between '%2' and '%3' "
                        "GROUP BY year_month ORDER BY year_month;").arg(info,beginTime,endTime);
    query.exec(sql);
    while (query.next())
    {
        result.append(query.value("Month").toString()+","+query.value("TotalRecords").toString());
    }
    return result;
}

/** 获取总统计数据
 * @brief GetMessageInterface::getStaticTotalNum
 * @param type
 * @return
 */
Q_INVOKABLE QStringList GetMessageInterface::getStaticTotalNum(int type){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString info;
    switch (type) {
    case 1:
        info="EquOperatingTime";//设备运行时间
        break;
    case 2:
        info="ExperimentalRunningTime";//实验运行时间
        break;
    case 3:
        info="TargetPeristalticPump";//打靶蠕动泵
        break;
    case 4:
        info="PurifyingPeristalticPump";//纯化蠕动泵
        break;
    case 5:
        info="CompressRubberPadTimes";//压缩机橡胶垫时间
        break;
    case 6:
        info="VacuumSuctionCupUseTime";//抽真空杯使用时间
        break;
    case 7:
        info="ExpansionClipUseTime";
        break;
    case 8:
        info="ClawUsageDuration";
        break;
    }
    QString sql;
    QStringList result;

    sql=QString("SELECT sum(%1)-(Select EquOperatingTimeDel From %1Del) AS TotalRecords FROM DataStatistics").arg(info);
    query.exec(sql);
    while (query.next()) {
        result.append(query.value("TotalRecords").toString());
    }

    sql=QString("Select %1 as Threshold From DataStatisticsThreshold").arg(info);
    query.exec(sql);
    while (query.next()) {
        result.append(query.value("Threshold").toString());
    }
    return result;
}

/** 重置统计数据
 * @brief GetMessageInterface::resetStaticNum
 * @param type
 */
Q_INVOKABLE void GetMessageInterface::resetStaticNum(int type){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString info;
    switch (type) {
    case 1:
        info="EquOperatingTime";
        break;
    case 2:
        info="ExperimentalRunningTime";
        break;
    case 3:
        info="TargetPeristalticPump";
        break;
    case 4:
        info="PurifyingPeristalticPump";
        break;
    case 5:
        info="CompressRubberPadTimes";
        break;
    case 6:
        info="VacuumSuctionCupUseTime";
        break;
    case 7:
        info="ExpansionClipUseTime";
        break;
    case 8:
        info="ClawUsageDuration";
        break;
    }
    QString sql=QString("Update DataStatisticsThreshold Set %1Del=(SELECT sum(%1) FROM DataStatistics)");
    query.exec(sql);
}

/** 连接能谱
 * @brief GetMessageInterface::connectEnergySpectrum
 * @param port 端口
 */
Q_INVOKABLE void GetMessageInterface::connectEnergySpectrum(QString port){
    //    QSqlDatabase db = dbHelper::openConnection();
    //    QSqlQuery query(db);
    //    QString sql=QString("Update IpInfo set port='%1' Where ConnectType='3'").arg(port);
    //    query.exec(sql);

    //    //    serialPortClient = new DataSerialportClient();
    //    serialPortClient->startAutoSend(100, port);
}

/** 读取辐射值
 * @brief GetMessageInterface::readRadiation
 * @param type 0开始 1关闭
 */
Q_INVOKABLE void GetMessageInterface::readRadiation(int type){
    cpsUdpClient= CpsUdpClient::getInstance();
    QString sendInfo=CommCommand::I().readRadiation(type==0?"01":"00");
    cpsUdpClient->ClientSendingData(CommonHelper::Common().GetSendData(sendInfo));
}


Q_INVOKABLE QString GetMessageInterface::getCurrentStepInfo(){
    QString module= CommonHelper::Common().getCurrentExpTypeName(StaticProperties::currentExpModule);
    QString info=StaticProperties::expLogList[StaticProperties::currentExpModule-1][StaticProperties::expStep]["ActionInfo"].toString();

    QString result=QString("当前步骤[%1] 步骤%2-%3").arg(module,QString::number(StaticProperties::expStep),info);
    return result;
}

Q_INVOKABLE void GetMessageInterface::reconnect(){
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString ip,port;
    QString sql="Select Ip,Port From IpInfo Where ConnectType='0'";
    query.exec(sql);
    while (query.next()) {
        ip=query.value("Ip").toString();
        port=query.value("Port").toString();
    }


    UdpClient *udpClient= UdpClient::getInstance();
    udpClient->ClientConnectToHost(ip, port.toInt());
    QString sendInfo=CommCommand::I().connectToLc();
    udpClient->ClientSendingData(CommonHelper::Common().GetSendData(sendInfo));

    CpsUdpClient *cpsudpClient= CpsUdpClient::getInstance();
    cpsudpClient->ClientConnectToHost(ip, 8090);
}
